package com.liuzhongni.wahahanews.headlineclass;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Environment;
import android.util.Log;

import com.android.volley.toolbox.ImageLoader;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * Created by dllo on 16/1/18.
 */
public class MyDiskCache implements ImageLoader.ImageCache {
    private String caCheDir = "";

    public MyDiskCache() {
        //判断sd储存卡存在  getExternalStorageState()获取sd卡状态
        if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
            //获取储存卡目录
            File root = Environment.getExternalStorageDirectory();
            //获取绝对路径  root.getAbsolutePath()
            File cacheFile = new File(root.getAbsolutePath()+"/cache");
            //如果不存在
            if(!cacheFile.exists()){
                //创建文件夹
                cacheFile.mkdir();
//                cacheFile.createNewFile() 创建文件加
            }
            caCheDir = cacheFile.getAbsolutePath();//绝对路径
        }
    }

    @Override
    public Bitmap getBitmap(String url) {
        url = url.substring(url.lastIndexOf("/"), url.lastIndexOf(".") + 4);
        return BitmapFactory.decodeFile(caCheDir + "/" + url);
    }

    @Override
    public void putBitmap(String url, Bitmap bitmap) {
        url = url.substring(url.lastIndexOf("/"), url.lastIndexOf(".") + 4);
        FileOutputStream fos = null;
        try {
            //初始化文件写入对象   添加路径
            fos = new FileOutputStream(caCheDir + "/" + url);
            //保存bitmap
            bitmap.compress(Bitmap.CompressFormat.JPEG,100,fos);
            Log.d("MyDiskCache", "bitmap.getRowBytes():" + bitmap.getRowBytes()*bitmap.getHeight()/1024);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }finally {
            if(null != fos){
                try {
                    //这么写 怎么都会关
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

}
